import * as api from '@/services/api';
import { Toast } from 'antd-mobile';

export default {
  namespace: 'central',
  state: {
    listData: [],
    page: 1,
    totalPage: 1,
    isLoading: false,
    hasMore: true,
    dataSource: [],
    clickCount: 0,
  },
  effects: {
    // @ts-ignore
    *getList(param: any, { call, put }) {
      const data = yield call(api.getList, param.payload);
      yield put({
        type: 'add',
        data: data.data,
      });
    },
    // @ts-ignore
    *removePublish(param: any, { call, put }) {
      const data = yield call(api.removePublish, param.payload);
      if (data) {
        yield put({
          type: 'deletePublish',
          payload: param.payload,
        });
      } else {
        Toast.fail('删除失败，请稍后再试！！', 1);
      }
    },
  },
  reducers: {
    add(state: any, action: any) {
      const { listData, page, totalPage } = action.data;
      let tempList = state.dataSource.concat(listData);
      return {
        ...state,
        listData: listData,
        dataSource: tempList,
        page: page + 1,
        totalPage: totalPage,
      };
    },

    countAdd(state: any) {
      return { ...state, clickCount: ++state.clickCount };
    },

    deletePublish(state: any, payload: any) {
      const { id } = payload.payload;
      let { listData, dataSource } = state;
      state.listData = listData.filter((element: any) => {
        return element.id !== id;
      });
      state.dataSource = dataSource.filter((element: any) => {
        return element.id !== id;
      });
      Toast.success('删除成功！', 1);
      return { ...state };
    },

    resetSource(state: any) {
      state.dataSource = [];
      state.listData = [];
      return { ...state };
    },
  },
};
